#!/usr/bin/env python

import pygame, math, random, os
from pygame.locals import *
from random import Random

global B_IMG
global TREE_IMG
global TREE_F1_IMG
global TREE_F2_IMG
global TREE_F3_IMG
global TREE_F4_IMG
global TREE_F5_IMG
global TREE_F6_IMG
global TREE_F7_IMG
global TREE_F8_IMG
global TREE_F9_IMG
global TREE_F10_IMG
global TREE_F11_IMG
global TREE_F12_IMG
global TREE_F13_IMG
global TREE_F14_IMG
global TREE_F15_IMG
global TREE_F16_IMG
global TREE_F17_IMG
global TREE_FALLEN_IMG
global MOUNT_IMG
global BRIDGE_IMG
global FENCE_H_IMG
global FENCE_V_IMG
global WALL_H_IMG
global WALL_V_IMG
global WATER_DD_IMG
global WATER_DL_IMG
global WATER_DR_IMG
global WATER_RD_IMG
global WATER_LD_IMG
global WATER_LR_IMG
global WATER_4_IMG
global WATER_3D_IMG
global WATER_3L_IMG
global WATER_3R_IMG
global WATER_3U_IMG



def loadImages():
	global B_IMG
	global TREE_IMG
	global TREE_F1_IMG
	global TREE_F2_IMG
	global TREE_F3_IMG
	global TREE_F4_IMG
	global TREE_F5_IMG
	global TREE_F6_IMG
	global TREE_F7_IMG
	global TREE_F8_IMG
	global TREE_F9_IMG
	global TREE_F10_IMG
	global TREE_F11_IMG
	global TREE_F12_IMG
	global TREE_F13_IMG
	global TREE_F14_IMG
	global TREE_F15_IMG
	global TREE_F16_IMG
	global TREE_F17_IMG
	global TREE_FALLEN_IMG
	global MOUNT_IMG
	global BRIDGE_H_IMG
	global BRIDGE_V_IMG
	global FENCE_H_IMG
	global FENCE_V_IMG
	global WALL_H_IMG
	global WALL_V_IMG
	global WATER_DD_IMG
	global WATER_DL_IMG
	global WATER_DR_IMG
	global WATER_RD_IMG
	global WATER_LD_IMG
	global WATER_LR_IMG
	global WATER_4_IMG
	global WATER_3D_IMG
	global WATER_3L_IMG
	global WATER_3R_IMG
	global WATER_3U_IMG

	B_IMG = pygame.image.load('bullet.png').convert_alpha() #Bullet image
	TREE_IMG = pygame.image.load('tree.png').convert_alpha()
	MOUNT_IMG = pygame.image.load('mount1.png').convert_alpha()
	BRIDGE_H_IMG = pygame.image.load('bridgeh.png').convert()
	BRIDGE_V_IMG = pygame.transform.rotate(BRIDGE_H_IMG,-90)
	FENCE_V_IMG = pygame.image.load('fencev.png').convert()
	FENCE_H_IMG = pygame.transform.rotate(FENCE_V_IMG,-90)
	WALL_V_IMG = pygame.image.load('wallv.png').convert()
	WALL_H_IMG = pygame.transform.rotate(WALL_V_IMG,-90)
	WATER_DD_IMG = pygame.image.load('riverdd.png').convert()
	WATER_DL_IMG = pygame.image.load('riverdl.png').convert_alpha()
	WATER_LD_IMG = pygame.transform.rotate(WATER_DL_IMG,90)
	WATER_RD_IMG = pygame.transform.rotate(WATER_LD_IMG,90)
	WATER_DR_IMG = pygame.transform.rotate(WATER_RD_IMG,90)
	WATER_LR_IMG = pygame.transform.rotate(WATER_DD_IMG,90)
	WATER_4_IMG = pygame.image.load('river4.png').convert()
	WATER_3D_IMG = pygame.image.load('river3d.png').convert()
	WATER_3L_IMG = pygame.transform.rotate(WATER_3D_IMG,-90)
	WATER_3R_IMG = pygame.transform.rotate(WATER_3D_IMG,90)
	WATER_3U_IMG = pygame.transform.rotate(WATER_3D_IMG,180)
	TREE_F1_IMG = pygame.image.load('treef1.png').convert_alpha()
	TREE_F2_IMG = pygame.image.load('treef2.png').convert_alpha()
	TREE_F3_IMG = pygame.image.load('treef3.png').convert_alpha()
	TREE_F4_IMG = pygame.image.load('treef4.png').convert_alpha()
	TREE_F5_IMG = pygame.image.load('treef5.png').convert_alpha()
	TREE_F6_IMG = pygame.image.load('treef6.png').convert_alpha()
	TREE_F7_IMG = pygame.image.load('treef7.png').convert_alpha()
	TREE_F8_IMG = pygame.image.load('treef8.png').convert_alpha()
	TREE_F9_IMG = pygame.image.load('treef9.png').convert_alpha()
	TREE_F10_IMG = pygame.image.load('treef10.png').convert_alpha()
	TREE_F11_IMG = pygame.image.load('treef11.png').convert_alpha()
	TREE_F12_IMG = pygame.image.load('treef12.png').convert_alpha()
	TREE_F13_IMG = pygame.image.load('treef13.png').convert_alpha()
	TREE_F14_IMG = pygame.image.load('treef14.png').convert_alpha()
	TREE_F15_IMG = pygame.image.load('treef15.png').convert_alpha()
	TREE_F16_IMG = pygame.image.load('treef16.png').convert_alpha()
	TREE_F17_IMG = pygame.image.load('treef17.png').convert_alpha()
	TREE_FALLEN_IMG = pygame.image.load('treefallen.png').convert_alpha()

class Bullet(pygame.sprite.Sprite):
	def gridFromX(self,x): return x/25
	def gridFromY(self,y): return y/25	
	def gridsContainingBullet(self):	
		grids = []
		x = self.gridFromX(self.position[0])
		y = self.gridFromY(self.position[1])
		grids.append((x,y))
		x2 = self.gridFromX(self.position[0]+self.width)
		if x2 != x and x2*25 < self.bg.get_width():
			grids.append((x2,y))
		y2 = self.gridFromY(self.position[1]+self.height)
		if y2 != y and y2*25 < self.bg.get_height():
			grids.append((x,y2))
			if x2 != x and x2*25 < self.bg.get_width():
				grids.append((x2,y2))
		return grids
	
	def __init__(self,shooter,backColor,mapGrid,bg):
		pygame.sprite.Sprite.__init__(self)
		global B_IMG
		self.image = B_IMG
		self.shooter = shooter
		self.backColor = backColor
		self.mapGrid = mapGrid
		self.bg = bg
		self.grids = []
		self.dirtyGrids = []
		self.width = 5 #Change?
		self.height = 5
		self.burnTree = 0
		self.active = 0
		self.position = (-10,-10)
		self.area = pygame.rect.Rect((-10,-10),(5,5))
	def fireBullet(self, pos, xdirection, ydirection):
		self.position = pos
		self.area = pygame.rect.Rect(pos,(self.width,self.height))
		self.xdirection = xdirection
		self.ydirection = ydirection
		self.active = 1
		
	def update(self):
		dx = 3
		dy = 3
		
		if self.active == 0: return
		
		lastPosition = self.position
		areaPosition = self.position
		movedHeight = self.height
		movedWidth = self.width
		if self.xdirection == "LEFT":
			if self.position[0] - dx < 0:
				self.active = 0
			else:
				self.position = (self.position[0] - dx,self.position[1])
				areaPosition = self.position
				movedWidth = self.width+dx
		elif self.xdirection == "RIGHT":
			if self.position[0] + self.width + dx > self.bg.get_width():
				self.active = 0
			else:
				self.position = (self.position[0] + dx,self.position[1])
				movedWidth = self.width+dx
				areaPosition = lastPosition
		if self.ydirection == "UP":
			if self.position[1] - dy < 0:
				self.active = 0
			else:
				self.position = (self.position[0],self.position[1] - dy)
				movedHeight = self.height+dy
				areaPosition = (areaPosition[0],self.position[1])
		elif self.ydirection == "DOWN":
			if self.position[1] + self.height + dy > self.bg.get_height():
				self.active = 0
			else:
				self.position = (self.position[0],self.position[1] + dy)
				movedHeight = self.height+dy
				areaPosition = (areaPosition[0],lastPosition[1])
		self.area = pygame.rect.Rect(areaPosition,(movedWidth,movedHeight))
		
		self.dirtyGrids = self.grids
		newGrids = self.gridsContainingBullet()
		for g in newGrids:
			if g not in self.dirtyGrids: self.dirtyGrids.append(g)
			if isinstance(self.mapGrid[g[0]][g[1]],Wall):
				if self.mapGrid[g[0]][g[1]].type == "WALL" or self.mapGrid[g[0]][g[1]].type == "FENCE":
					self.active = 0
				if self.mapGrid[g[0]][g[1]].type == "TREE" and self.mapGrid[g[0]][g[1]].imageState < 10:
					self.burnTree = self.mapGrid[g[0]][g[1]]
					self.active = 0
		self.grids = newGrids
		self.rect = pygame.rect.Rect(self.position,(self.width,self.height))
		
	def draw(self,bg):		
		pygame.draw.rect(bg,self.backColor,self.area)
		drawAfter = []
		for d in self.dirtyGrids:
			if isinstance(self.mapGrid[d[0]][d[1]],Wall): 
				self.mapGrid[d[0]][d[1]].draw(bg)
				if self.mapGrid[d[0]][d[1]].type == "TREE":
					drawAfter.append(self.mapGrid[d[0]][d[1]])
			if d[1] < bg.get_height()/25 - 1 and isinstance(self.mapGrid[d[0]][d[1] + 1],Wall) and self.mapGrid[d[0]][d[1] + 1].type == "TREE":
				drawAfter.append(self.mapGrid[d[0]][d[1]+1])		
		
		if self.active: bg.blit(self.image,self.position)
		for a in drawAfter:
			a.draw(bg)
	
class GameMap():
	'''This is the class for the game map'''
	def __init__(self,bg,seed = None):
		directions = {0:"LEFT",1:"RIGHT",2:"UP",3:"DOWN"}
		
		width = bg.get_width()
		height = bg.get_height()
		
		columnWidth = 25
		rowHeight = 25
		columnCount = width/columnWidth
		rowCount = height/rowHeight
		
		def wallsInRange(grid,topLeft,bottomRight):
			walls = []
			for x in range(topLeft[0],bottomRight[0]):
				for y in range(topLeft[1],bottomRight[1]):
					
					if x >= 0 and x < columnCount and y >=0 and y < rowCount and grid[x][y] != 0:
						walls.append(grid[x][y])
			return walls
			
		def placeWallInRange(grid,nWall,topLeft,bottomRight):
			for x in range(topLeft[0],bottomRight[0]):
				for y in range(topLeft[1],bottomRight[1]):
					if x >= 0 and x < columnCount and y >=0 and y < rowCount:
						grid[x][y] = nWall
			
		def xFromGrid(x): return x*columnWidth
		def yFromGrid(y): return y*rowHeight	
		
		rand = Random()
		rand.seed(seed)
		
		ok = 0
		while ok != 2:	
			waters = []
			trees = []
			walls = []
			fences = []
			mountains = []
			bridges = []
			
			mapGrid = [[0 for y in range(rowCount)] for x in range(columnCount)]
			
			#Generate rivers
			pWater = Wall("WATER",0,0,"DOWN")
			riverCount = rand.randint(0,2*columnCount / 7)
			riverStart = [rand.randrange(0,columnCount) for x in range(riverCount)]
			
			for startx in riverStart:
				x = startx
				y = 0
				direction = "DOWN"
				lastDirection = 'D'
				currentDirection = 'D'
				while y < rowCount:
					p = rand.randint(0,6)
					if direction == "DOWN":
						lastDirection = 'D'
						if p == 5: 
							direction = "LEFT"
							currentDirection = 'L'
						elif p == 6: 
							direction = "RIGHT"
							currentDirection = 'R'
					else:
						if direction == 'LEFT':
								lastDirection = 'R'
						else:
								lastDirection = 'L'
						if p <= 4: 
							direction = "DOWN"
							currentDirection = 'D'
				
		

					if (lastDirection == 'L' or lastDirection == 'R') and (currentDirection == 'L' or currentDirection == 'R'):
						newDirection = 'LR'
					else:
						newDirection = lastDirection+currentDirection
					
					if x >= 0 and x < columnCount:
						if mapGrid[x][y] != 0 and isinstance(mapGrid[x][y],Wall):
							contents = mapGrid[x][y]
							if contents.direction == 'DD' and lastDirection == 'R' or contents.direction == 'RD' and lastDirection == 'D':
								mapGrid[x][y] = Wall("WATER",xFromGrid(x),yFromGrid(y),'3R')
								waters[waters.index(contents)] = mapGrid[x][y]
							elif contents.direction == 'DD' and lastDirection == 'L' or contents.direction == 'LD' and lastDirection == 'D':
								mapGrid[x][y] = Wall("WATER",xFromGrid(x),yFromGrid(y),'3L')
								waters[waters.index(contents)] = mapGrid[x][y]
							elif contents.direction == 'RD' and lastDirection == 'L' or contents.direction == 'LD' and lastDirection == 'R':
								mapGrid[x][y] = Wall("WATER",xFromGrid(x),yFromGrid(y),'3D')
								waters[waters.index(contents)] = mapGrid[x][y]
							elif contents.direction == 'DL' and lastDirection == 'R' or contents.direction == 'DR' and lastDirection == 'L' or contents.direction == 'LR' and lastDirection == 'D':
								mapGrid[x][y] = Wall("WATER",xFromGrid(x),yFromGrid(y),'3U')
								waters[waters.index(contents)] = mapGrid[x][y]
							elif contents.direction == '3R' and lastDirection == 'L' or contents.direction == '3L' and lastDirection == 'R' or contents.direction == '3D' and lastDirection == 'D':
								mapGrid[x][y] = Wall("WATER",xFromGrid(x),yFromGrid(y),'ALL')
								waters[waters.index(contents)] = mapGrid[x][y]
							break	
						else:
							mapGrid[x][y] = Wall("WATER",xFromGrid(x),yFromGrid(y),newDirection)
							waters.append(mapGrid[x][y])
						
					if direction == "DOWN":
						y += 1
					elif direction == "LEFT":
						x -= 1
					elif direction == "RIGHT":
						x += 1
			
			#Generate bridges
			pBridge = Wall("BRIDGE",0,0,"RIGHT")
			bridgeCount = rand.randint(0,3*riverCount)
			for b in range(bridgeCount):
				w = waters[rand.randint(0,len(waters)-1)]
				gx = w.x/columnWidth
				gy = w.y/rowHeight
				if w.direction == "DD":
					mapGrid[gx][gy] = Wall("BRIDGE",w.x,w.y,"H")
					bridges.append(mapGrid[gx][gy])
				elif w.direction == "LR": 
					mapGrid[gx][gy] = Wall("BRIDGE",w.x,w.y,"V")
					bridges.append(mapGrid[gx][gy])
			ok = 0
			for i in range(columnCount):
				for j in range(rowCount):
					if mapGrid[i][j] == 0: 
						ok += 1
					if ok == 2: break
				if ok == 2: break
		
		#generate player start locations
		ok = 0
		while not ok:
			x = rand.randrange(0,columnCount)
			y = rand.randrange(0,rowCount)
			if mapGrid[x][y] == 0: ok = 1
		mapGrid[x][y] = "player1Start"
		p1Start = (x*25,y*25)
		
		ok = 0
		while not ok:
			x = rand.randrange(0,columnCount)
			y = rand.randrange(0,rowCount)
			if mapGrid[x][y] == 0: ok = 1
		mapGrid[x][y] = "player2Start"
		p2Start = (x*25,y*25)
				
		#Generate walls and fences
		pWall = Wall("WALL",0,0,"RIGHT")
		wallsCount = rand.randint(0,rowCount*columnCount/50)	
		lastType = "FENCE"	
		def placeWall(x,y,direction,lastType,grid,walls):
			if rand.randint(0,2) == 0:
				if lastType == "FENCE":
					lastType = "WALL"
				else:
					lastType = "FENCE"
				
			if grid[x][y] == 0:
				grid[x][y] = Wall(lastType,x*25,y*25,direction)
				walls.append(grid[x][y])
				if direction == "UP" or direction == "DOWN":
					if y > 0:
						if rand.randint(0,2) != 0:
							lastType = placeWall(x,y-1,direction,lastType,grid,walls)
					if y < rowCount - 1:
						if rand.randint(0,2) != 0:
							lastType = placeWall(x,y+1,direction,lastType,grid,walls)						
				else:
					if x > 0:
						if rand.randint(0,2) != 0:
							lastType = placeWall(x-1,y,direction,lastType,grid,walls)
					if x < columnCount - 1:
						if rand.randint(0,2) != 0:
							lastType = placeWall(x+1,y,direction,lastType,grid,walls)
			return lastType					
				
		for w in range(wallsCount):
			x = rand.randrange(0,columnCount)
			y = rand.randrange(0,rowCount)
			direction = directions[rand.randint(0,3)]		
			lastType = placeWall(x,y,direction,lastType,mapGrid,walls)
		
		
		#generate trees
		pTree = Wall("TREE",0,0)
		treeType = rand.randint(0,3)
		#treetype:
		#0: no trees
		#1: sporatic trees
		#2: forests
		#3: forests and sporatic trees
		
		def maybePlaceTrees(x,y):
			if mapGrid[x][y] == 0:
				mapGrid[x][y] = Wall("TREE",xFromGrid(x),yFromGrid(y)-(pTree.height-rowHeight))
				trees.append(mapGrid[x][y])
				if x > 0:
					if rand.randint(0,2) == 0:
						maybePlaceTrees(x-1,y)
				if x < columnCount - 1:
					if rand.randint(0,2) == 0:
						maybePlaceTrees(x+1,y)
				if y > 0:
					if rand.randint(0,2) == 0:
						maybePlaceTrees(x,y-1)
				if y < rowCount - 1:
					if rand.randint(0,2) == 0:
						maybePlaceTrees(x,y+1)
						
		if treeType == 1:
			treeCount = rand.randint(0,rowCount*columnCount/10)
			for t in range(treeCount):
				x = rand.randrange(0,columnCount)
				y = rand.randrange(0,rowCount)
				if mapGrid[x][y] == 0:
					mapGrid[x][y] = Wall("TREE",xFromGrid(x),yFromGrid(y)-(pTree.height-rowHeight))
					trees.append(mapGrid[x][y])
		elif treeType == 2:
			forestCount = rand.randint(0,rowCount*columnCount/100)
			for f in range(forestCount):
				fx = rand.randrange(0,columnCount)
				fy = rand.randrange(0,rowCount)
				maybePlaceTrees(fx,fy)
		elif treeType == 3:
			treeCount = rand.randint(0,rowCount*columnCount/15)
			for t in range(treeCount):
				x = rand.randrange(0,columnCount)
				y = rand.randrange(0,rowCount)
				if mapGrid[x][y] == 0:
					mapGrid[x][y] = Wall("TREE",xFromGrid(x),yFromGrid(y)-(pTree.height-rowHeight))
					trees.append(mapGrid[x][y])
			forestCount = rand.randint(0,rowCount*columnCount/115)
			for f in range(forestCount):
				fx = rand.randrange(0,columnCount)
				fy = rand.randrange(0,rowCount)
				maybePlaceTrees(fx,fy)
		'''
		I am leaving out mountains for now, the image isnt very good and they dont add much to the game.
		#generate mountains
		pMount = Wall("MOUNT",0,0)
		mountCount = rand.randint(0,4)
		for m in range(mountCount):
			x = rand.randint(0,columnCount)
			y = rand.randint(0,rowCount)
			if not wallsInRange(mapGrid,(x,y),(x+4,y+4)):
				nMount = Wall("MOUNT",x*25,y*25)
				mountains.append(nMount)
				placeWallInRange(mapGrid,nMount,(x,y),(x+4,y+4))
		'''
				
		self.grid = mapGrid
		self.columnCount = columnCount
		self.rowCount = rowCount
		self.color = (0,100,0)
		self.p1Start = p1Start
		self.p2Start = p2Start
		self.waters = waters
		self.bridges = bridges
		self.trees = trees
		self.fences = fences
		self.walls = walls
	

class Shooter(pygame.sprite.Sprite):
	'''This is the class for the main character sprites'''
	
	def gridFromX(self,x): return x/25
	def gridFromY(self,y): return y/25
	def gridsContainingPlayer(self):

			
		grids = []
		x = self.gridFromX(self.position[0])
		y = self.gridFromY(self.position[1])
		grids.append((x,y))
		x2 = self.gridFromX(self.position[0]+self.width)
		if x2 != x:
			grids.append((x2,y))
		y2 = self.gridFromY(self.position[1]+self.height)
		if y2 != y:
			grids.append((x,y2))
			if x2 != x:
				grids.append((x2,y2))
		return grids
		
	def canPlayerMove(self,direction,distance):
		x = self.gridFromX(self.position[0])
		y = self.gridFromY(self.position[1])
		
		if self.gridFromY(self.position[1] + self.height) != y:
			x2 = 1
		else:
			x2 = 0
		if self.gridFromX(self.position[0] + self.width) != x:
			y2 = 1
		else:
			y2 = 0
			
		self.rect = pygame.rect.Rect(self.position,(self.width,self.height))
		self.opponent.rect = pygame.rect.Rect((self.opponent.position),(self.opponent.width,self.opponent.height))

		if direction == "LEFT":
			self.rect = pygame.rect.Rect((self.position[0] - distance,self.position[1]),(self.width,self.height))
			if self.position[0] % 25 - distance < 0 and x > 0:
				if isinstance(self.mapGrid[x-1][y],Wall) and (self.mapGrid[x-1][y].type == "WATER" or self.mapGrid[x-1][y].type == "FENCE" or self.mapGrid[x-1][y].type == "WALL"): 
					return 0
				if x2 and isinstance(self.mapGrid[x-1][y+1],Wall) and (self.mapGrid[x-1][y+1].type == "WATER" or self.mapGrid[x-1][y+1].type =="FENCE" or self.mapGrid[x-1][y+1].type == "WALL"):
					return 0
		if direction == "RIGHT":
			self.rect = pygame.rect.Rect((self.position[0] + distance,self.position[1]),(self.width,self.height))
			if (self.position[0] + self.width) % 25 + distance >= 25 and x < self.bg.get_width()/25 - 1:
				if isinstance(self.mapGrid[x+1][y],Wall) and (self.mapGrid[x+1][y].type == "WATER" or self.mapGrid[x+1][y].type == "FENCE" or self.mapGrid[x+1][y].type == "WALL"): 
					return 0
				if x2 and isinstance(self.mapGrid[x+1][y+1],Wall) and (self.mapGrid[x+1][y+1].type == "WATER" or self.mapGrid[x+1][y+1].type =="FENCE" or self.mapGrid[x+1][y+1].type == "WALL"):
					return 0		
		if direction == "UP":
			self.rect = pygame.rect.Rect((self.position[0],self.position[1] - distance),(self.width,self.height))
			if self.position[1] % 25 - distance < 0 and y > 0:
				if isinstance(self.mapGrid[x][y-1],Wall) and (self.mapGrid[x][y-1].type == "WATER" or self.mapGrid[x][y-1].type == "FENCE" or self.mapGrid[x][y-1].type == "WALL"): 
					return 0
				if y2 and isinstance(self.mapGrid[x+1][y-1],Wall) and (self.mapGrid[x+1][y-1].type == "WATER" or self.mapGrid[x+1][y-1].type =="FENCE" or self.mapGrid[x+1][y-1].type == "WALL"):
					return 0
		if direction == "DOWN":
			self.rect = pygame.rect.Rect((self.position[0],self.position[1] + distance),(self.width,self.height))
			if (self.position[1] + self.height) % 25 + distance >= 25 and x < self.bg.get_height()/25 - 1:
				if isinstance(self.mapGrid[x][y+1],Wall) and (self.mapGrid[x][y+1].type == "WATER" or self.mapGrid[x][y+1].type == "FENCE" or self.mapGrid[x][y+1].type == "WALL"): 
					return 0
				if y2 and isinstance(self.mapGrid[x+1][y+1],Wall) and (self.mapGrid[x+1][y+1].type == "WATER" or self.mapGrid[x+1][y+1].type =="FENCE" or self.mapGrid[x+1][y+1].type == "WALL"):
					return 0		
		if pygame.sprite.collide_rect(self,self.opponent): return 0

		return 1
				
	def __init__(self, player, gameMap, bg):
	
		pygame.sprite.Sprite.__init__(self) #sprite initializer
		self.player = player
		self.health = 100
		self.xdirection = 0
		self.ydirection = 0
		self.lastXDirection = "LEFT"
		self.lastYDirection = "UP"
		self.testImage = pygame.image.load('test.png').convert()
		self.backColor = gameMap.color
		self.fallenTrees = []
		self.width = 18
		self.height = 21
		self.iShot = 0
		self.objCount = 0
		self.shot = 0
		self.bullet = []
		self.currentBullet = 0
		self.dirtyGrids = []
		self.mapGrid = gameMap.grid
		self.bg = bg
		
	
		if self.player == 1: 

			#faceUp = pygame.image.load('foo.png').convert()
			#faceDown = pygame.image.load('foo.png').convert()
			#faceRight = pygame.image.load('foo.png').convert()
			#faceLeft = pygame.image.load('foo.png').convert()
			#faceUpRight = pygame.image.load('foo.png').convert()
			#faceUpLeft = pygame.image.load('foo.png').convert()
			#faceDownRight = pygame.image.load('foo.png').convert()
			#faceDownLeft = pygame.image.load('foo.png').convert()
			self.leftKey = K_LEFT
			self.rightKey = K_RIGHT
			self.upKey = K_UP
			self.downKey = K_DOWN
			self.position = gameMap.p1Start
			self.shootKey = K_RETURN
			
			for i in range(5):
				self.bullet.append(Bullet(self,self.backColor,self.mapGrid,self.bg)) #For friendly fire
		
		if self.player == 2: 
			#faceUp = pygame.image.load('foo.png').convert()
			#faceDown = pygame.image.load('foo.png').convert()
			#faceRight = pygame.image.load('foo.png').convert()
			#faceLeft = pygame.image.load('foo.png').convert()
			#faceUpRight = pygame.image.load('foo.png').convert()
			#faceUpLeft = pygame.image.load('foo.png').convert()
			#faceDownRight = pygame.image.load('foo.png').convert()
			#faceDownLeft = pygame.image.load('foo.png').convert()			
			self.leftKey = K_a
			self.rightKey = K_d
			self.upKey = K_w
			self.downKey = K_s
			self.position = gameMap.p2Start
			self.shootKey = K_SPACE

			for i in range(5):
				self.bullet.append(Bullet(self,self.backColor,self.mapGrid,self.bg))
		
		self.grids = self.gridsContainingPlayer()
		
	def update(self): 
		'''Update movements of sprite shooter'''
		#position[0] == X coord ### position[1] == Y coord
		dx = 2
		dy = 2
		self.image = self.testImage
		lastPosition = self.position
		areaPosition = self.position
		movedHeight = self.height
		movedWidth = self.width
		self.area = pygame.rect.Rect(self.position,(self.width,self.height))
		self.rect = self.area
		if self.xdirection == "LEFT" and self.position[0] - dx >= 0 and self.canPlayerMove(self.xdirection,dx):
			self.position = (self.position[0] - dx,self.position[1])
			areaPosition = self.position
			movedWidth = self.width+dx
		elif self.xdirection == "RIGHT" and self.position[0] + self.width + dx < self.bg.get_width() and self.canPlayerMove(self.xdirection,dx):
			self.position = (self.position[0] + dx,self.position[1])
			movedWidth = self.width+dx
			areaPosition = lastPosition
		if self.ydirection == "UP" and self.position[1] - dy >= 0 and self.canPlayerMove(self.ydirection,dy):
			self.position = (self.position[0],self.position[1] - dy)
			movedHeight = self.height+dy
			areaPosition = (areaPosition[0],self.position[1])
		elif self.ydirection == "DOWN" and self.position[1] + self.height + dy < self.bg.get_height() and self.canPlayerMove(self.ydirection,dy):
			self.position = (self.position[0],self.position[1] + dy)
			movedHeight = self.height+dy
			areaPosition = (areaPosition[0],lastPosition[1])
		self.area = pygame.rect.Rect(areaPosition,(movedWidth,movedHeight))
		self.dirtyGrids = self.grids
		self.newGrids = self.gridsContainingPlayer()
		for g in self.newGrids:
		 	t = self.mapGrid[g[0]][g[1]]
		 	if isinstance(t,Wall) and t.type == "TREE" and t.imageState < 17:
		 		t.imageState = 18
		 		t.image = t.images[18]
		 		self.fallenTrees.append(t)
			if g not in self.dirtyGrids: self.dirtyGrids.append(g)
		self.grids = self.newGrids
		
	def draw(self,bg):
		pygame.draw.rect(bg,self.backColor,self.area)
		drawAfter = []
		for d in self.dirtyGrids:
			if isinstance(self.mapGrid[d[0]][d[1]],Wall): 
				self.mapGrid[d[0]][d[1]].draw(bg)
				if self.mapGrid[d[0]][d[1]].type == "TREE":
					drawAfter.append(self.mapGrid[d[0]][d[1]])
			if d[1] < bg.get_height()/25 - 1 and isinstance(self.mapGrid[d[0]][d[1] + 1],Wall) and self.mapGrid[d[0]][d[1] + 1].type == "TREE":
				drawAfter.append(self.mapGrid[d[0]][d[1]+1])		
		bg.blit(self.image,self.position)	
		bg.blit(self.opponent.image,self.opponent.position)
		def drawOrder(x,y):
			return x.order - y.order
		drawAfter.sort(drawOrder)
		for a in drawAfter:
			a.draw(bg)
		
	def updateHealth(self,damage): 
		'''Update health of sprite'''
		self.health -= damage
		if self.health > 0:
		   return 1
		else:
		   return 0

class Wall(pygame.sprite.Sprite):
	'''class of all blocking boundries'''
		
	def __init__(self,type,x,y,direction = 0):
		self.type = type
		self.x = x
		self.y = y
		self.direction = direction
		
		global B_IMG
		global TREE_IMG
		global TREE_F1_IMG
		global TREE_F2_IMG
		global TREE_F3_IMG
		global TREE_F4_IMG
		global TREE_F5_IMG
		global TREE_F6_IMG
		global TREE_F7_IMG
		global TREE_F8_IMG
		global TREE_F9_IMG
		global TREE_F10_IMG
		global TREE_F11_IMG
		global TREE_F12_IMG
		global TREE_F13_IMG
		global TREE_F14_IMG
		global TREE_F15_IMG
		global TREE_F16_IMG
		global TREE_F17_IMG
		global TREE_FALLEN_IMG
		global MOUNT_IMG
		global BRIDGE_IMG
		global FENCE_H_IMG
		global FENCE_V_IMG
		global WALL_H_IMG
		global WALL_V_IMG
		global WATER_DD_IMG
		global WATER_DL_IMG
		global WATER_DR_IMG
		global WATER_RD_IMG
		global WATER_LD_IMG
		global WATER_LR_IMG
		global WATER_4_IMG
		global WATER_3D_IMG
		global WATER_3L_IMG
		global WATER_3R_IMG

		if direction == "LEFT" or direction == "RIGHT": 
			horizontal = 1
		else:
			horizontal = 0
			
		if type == "TREE":
			self.height = 37
			self.width = 25
			self.imageState = 0
			self.drawTime = 0
			self.image = TREE_IMG
			self.images = [TREE_IMG,TREE_F1_IMG,TREE_F2_IMG,TREE_F3_IMG,TREE_F4_IMG,TREE_F5_IMG,TREE_F6_IMG,TREE_F7_IMG,TREE_F8_IMG,TREE_F9_IMG,TREE_F10_IMG,TREE_F11_IMG,TREE_F12_IMG,TREE_F13_IMG,TREE_F14_IMG,TREE_F15_IMG,TREE_F16_IMG,TREE_F17_IMG,TREE_FALLEN_IMG]

			
		elif type == "MOUNT":
			self.height = 100
			self.width = 100
			self.image = MOUNT_IMG

		elif type == "WATER":
			self.height = 25
			self.width = 25
			if direction == "DD":
				self.image = WATER_DD_IMG
			elif direction == "DL":
				self.image = WATER_DL_IMG
			elif direction == "DR":
				self.image = WATER_DR_IMG
			elif direction == "RD":
				self.image = WATER_RD_IMG
			elif direction == "LD":
				self.image = WATER_LD_IMG
			elif direction == "LR":
				self.image = WATER_LR_IMG
			elif direction == '3D':
				self.image = WATER_3D_IMG
			elif direction == '3L':
				self.image = WATER_3L_IMG
			elif direction == '3R':
				self.image = WATER_3R_IMG
			elif direction == '3U':
				self.image = WATER_3U_IMG
			elif direction == 'ALL':
				self.image = WATER_4_IMG
				
		elif type == "BRIDGE":
			self.height = 25
			self.width = 25
			if direction == "H":
				self.image = BRIDGE_H_IMG
			else:
				self.image = BRIDGE_V_IMG
				
		elif type == "WALL":
			if horizontal:
				self.height = 25
				self.width = 25
				self.image = WALL_H_IMG
			else:
				self.height = 25
				self.width = 25
				self.image = WALL_V_IMG

		elif type == "FENCE":
			if horizontal:
				self.height = 25
				self.width = 25
				self.image = FENCE_H_IMG
			else:
				self.height = 25
				self.width = 25
				self.image = FENCE_V_IMG
			
		self.area = pygame.rect.Rect((x,y),(self.width,self.height))

	def draw(self,bg):
		bg.blit(self.image,self.area)
		
		
def Game(screen,bg):
	gameMap = GameMap(bg)	
		
	player1 = Shooter(1,gameMap,bg)
	player2 = Shooter(2,gameMap,bg)
	player1.opponent = player2
	player2.opponent = player1

	bg.fill(gameMap.color)
	
	for r in gameMap.waters:
		bg.blit(r.image,r.area)
	for b in gameMap.bridges:
		bg.blit(b.image,b.area)
	for w in gameMap.walls:
		bg.blit(w.image,w.area)
	treeOrder = 0
	for y in range(gameMap.rowCount):
		for x in range(gameMap.columnCount):
				if isinstance(gameMap.grid[x][y],Wall) and gameMap.grid[x][y].type == "TREE":
					t = gameMap.grid[x][y]
					bg.blit(t.image,t.area)
					gameMap.grid[x][y].order = treeOrder
					gameMap.grid[x][y].rect = t.area
					t.x = x
					t.y = y
					treeOrder += 1
					
		
	
	screen.blit(bg,(0,0))
	pygame.display.flip()

	
	def treeOrder(x,y): return x.order - y.order

	def updateGame():
		bulletRects = []
		treeRects = []
		activeBullets = []
		burning = []
		fallen = []
		for p in [player1,player2]:
			if p.shot == 1:
				p.bullet[p.currentBullet].active = 0
				bulletRects.append(pygame.rect.Rect(p.bullet[p.currentBullet].position,(p.bullet[p.currentBullet].width,p.bullet[p.currentBullet].height)))
				p.bullet[p.currentBullet].draw(bg)
				p.bullet[p.currentBullet].fireBullet(p.position, p.lastXDirection, p.lastYDirection)
				p.currentBullet += 1
				if p.currentBullet > 4:
					p.currentBullet = 0
				p.shot = 0
			
			fallen += p.fallenTrees
			p.fallenTrees = []

			for b in p.bullet:
				b.update()
				b.draw(bg)
				bulletRects.append(b.area)
				if b.active: activeBullets.append(b)
				if b.burnTree and b.burnTree not in burning: burning.append(b.burnTree)
				
			p.update()

		burning.sort(treeOrder)
		fallen.sort(treeOrder)
		for t in burning:
			if t.imageState < 17 and t.drawTime == 0:
				t.drawTime = 1
		   		t.imageState += 1
				t.image = t.images[t.imageState]
				pygame.draw.rect(bg,player1.backColor,t.area)
				if t.y > 0 and isinstance(player1.mapGrid[t.x][t.y-1],Wall):
					player1.mapGrid[t.x][t.y-1].draw(bg)
				bg.blit(t.image,t.area)	
				if t.y < bg.get_height()/25 - 1 and isinstance(player1.mapGrid[t.x][t.y+1],Wall):
					player1.mapGrid[t.x][t.y+1].draw(bg)
				treeRects.append(t.rect)
			
			elif t.drawTime == 1: t.drawTime = 0

		for f in fallen:
			pygame.draw.rect(bg,player1.backColor,f.area)
			if f.y > 0 and isinstance(player1.mapGrid[f.x][f.y-1],Wall):
				player1.mapGrid[f.x][f.y-1].draw(bg)
			bg.blit(f.image,f.area)
			if f.y < bg.get_height()/25 - 1 and isinstance(player1.mapGrid[f.x][f.y+1],Wall):
				player1.mapGrid[f.x][f.y+1].draw(bg)
			treeRects.append(f.rect)

		for b in activeBullets:
			if pygame.sprite.collide_rect(b,b.shooter.opponent):
				b.shooter.opponent.updateHealth(10)	
				bulletRects.append(b.rect)
				b.active = 0
		player1.draw(bg)
		player2.draw(bg)

		dirtyRects = [player1.area,player2.area]+bulletRects+treeRects
		screen.blit(bg,(0,0))
		pygame.display.update(dirtyRects)
		
		
	startTime = pygame.time.get_ticks()	
	lastTime = startTime
	updateGame()
	
	leftDown1 = 0
	rightDown1 = 0
	upDown1 = 0
	downDown1 = 0	
	leftDown2 = 0
	rightDown2 = 0
	upDown2 = 0
	downDown2 = 0
	
	
	while 1:
		for event in pygame.event.get():
			if event.type == KEYDOWN:
				if event.key == player1.leftKey: 
					player1.xdirection = "LEFT"
					player1.lastXDirection = player1.xdirection
					leftDown1 = 1
				elif event.key == player1.rightKey:
					player1.xdirection = "RIGHT"
					player1.lastXDirection = player1.xdirection
					rightDown1 = 1
				elif event.key == player1.upKey:
					player1.ydirection = "UP"
					player1.lastYDirection = player1.ydirection
					upDown1 = 1
				elif event.key == player1.downKey:
					player1.ydirection = "DOWN"
					player1.lastYDirection = player1.ydirection
					downDown1 = 1
				elif event.key == player2.leftKey:
					player2.xdirection = "LEFT"
					player2.lastXDirection = player2.xdirection
					leftDown2 = 1
				elif event.key == player2.rightKey:
					player2.xdirection = "RIGHT"
					player2.lastXDirection = player2.xdirection
					rightDown2 = 1
				elif event.key == player2.upKey:
					player2.ydirection = "UP"
					player2.lastYDirection = player2.ydirection
					upDown2 = 1
				elif event.key == player2.downKey:
					player2.ydirection = "DOWN"
					player2.lastYDirection = player2.ydirection
					downDown2 = 1
				elif event.key == player1.shootKey: #Shooting for player 1
					player1.shot = 1
				elif event.key == player2.shootKey:
					player2.shot = 1
				elif event.key == K_BACKSPACE:
					Game(screen,bg)
					return
					
			elif event.type == KEYUP:
				if event.key == player1.leftKey: 
					if rightDown1:	
						player1.xdirection = "RIGHT"
						player1.lastXDirection = player1.xdirection
					else:
						player1.xdirection = 0
					leftDown1 = 0
			
				elif event.key == player1.rightKey:
					if leftDown1:
						player1.xdirection = "LEFT"
						player1.lastXDirection = player1.xdirection
					else:
						player1.xdirection = 0
					rightDown1 = 0
				elif event.key == player1.upKey :
					if downDown1:
						player1.ydirection = "DOWN"
						player1.lastYDirection = player1.ydirection
					else:
						player1.ydirection = 0
					upDown1 = 0
					
				elif event.key == player1.downKey:
					if upDown1:
						player1.ydirection = "UP"
						player1.lastYDirection = player1.ydirection
					else:
						player1.ydirection = 0
					downDown1 = 0
					
				elif event.key == player2.leftKey: 
					if rightDown2:	
						player2.xdirection = "RIGHT"
						player2.lastXDirection = player2.xdirection
					else:
						player2.xdirection = 0
					leftDown2 = 0
			
				elif event.key == player2.rightKey:
					if leftDown2:
						player2.xdirection = "LEFT"
						player2.lastXDirection = player2.xdirection
					else:
						player2.xdirection = 0
					rightDown2 = 0
					
				elif event.key == player2.upKey :
					if downDown2:
						player2.ydirection = "DOWN"
						player2.lastYDirection = player2.ydirection
					else:
						player2.ydirection = 0
					upDown2 = 0
					
				elif event.key == player2.downKey:
					if upDown2:
						player2.ydirection = "UP"
						player2.lastYDirection = player2.ydirection
					else:
						player2.ydirection = 0
					downDown2 = 0	
		if (leftDown1 or rightDown1) and not (upDown1 or downDown1):
			player1.lastYDirection = 0
		if (upDown1 or downDown1) and not (leftDown1 or rightDown1):
			player1.lastXDirection = 0
		if (leftDown2 or rightDown2) and not (upDown2 or downDown2):
			player2.lastYDirection = 0
		if (upDown2 or downDown2) and not (leftDown2 or rightDown2):
			player2.lastXDirection = 0
			
		currentTime = pygame.time.get_ticks()
		#this number controls the game speed
		if currentTime - lastTime >= 10:
			lastTime = currentTime
			updateGame()
			
def Menu(screen):

	bg = pygame.Surface(screen.get_size())
	bg = bg.convert()

	loadImages() 
	
	#change which menu is selected
	def updateMenu(itemNumber): 
		bg.fill((0, 0, 255))
	
		font = pygame.font.Font(None,36)
		text = font.render("Pending War",1,(255,255,0))
		textPosition = text.get_rect(centerx=bg.get_width()/2)
		bg.blit(text,textPosition)
		
		startText = font.render("Start Game", 1, (255,255,0))
		quitText = font.render("Quit", 1, (255,255, 0))	
		
		if itemNumber == 0:
			startText = font.render("> Start Game <", 1, (255,255,0))						
		elif itemNumber == 1:
			quitText = font.render("> Quit <", 1, (255,255, 0))
		textPosition = startText.get_rect(centerx=bg.get_width()/2, centery=100)
		bg.blit(startText, textPosition)
		textPosition = quitText.get_rect(centerx=bg.get_width()/2, centery=130)
		bg.blit(quitText, textPosition)	
		
		screen.blit(bg,(0,0))
		pygame.display.flip()
	
	#Menu event loop
	selectedMenuItem = 0
	itemCount = 2
	userQuit = 0
	updateMenu(selectedMenuItem)
	while 1:
		for event in pygame.event.get():
			if event.type == QUIT:
				pygame.quit()
				return
			if event.type == KEYDOWN:
				if event.key == K_DOWN:
					selectedMenuItem = (selectedMenuItem + 1) % itemCount
				elif event.key == K_UP:
					selectedMenuItem = (selectedMenuItem - 1) % itemCount
				elif event.key == K_RETURN:
					if selectedMenuItem == 0:
						Game(screen,bg)
					elif selectedMenuItem == 1:
						userQuit = 1
						break
			updateMenu(selectedMenuItem)
		if userQuit: break
			
	
		

		
def main():
	pygame.init()
	pygame.display.set_caption("Game Pending Title, or an idea for that matter")
	screen = pygame.display.set_mode((475, 475))
	pygame.mouse.set_visible(0)
	Menu(screen)
	print "Goodbye"
	
if __name__ == "__main__": main()
